from flask import render_template, redirect, url_for, flash, request
from flask_login import current_user, login_required
from app import db
from app.admin import bp
from app.models import User
from app.decorators import admin_required
from app.admin.forms import UserEditForm

@bp.route('/')
@login_required
@admin_required
def index():
    return render_template('admin/index.html', title='管理面板')

@bp.route('/users')
@login_required
@admin_required
def users():
    users = User.query.all()
    return render_template('admin/users.html', title='用户管理', users=users)

@bp.route('/users/<int:id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_user(id):
    user = User.query.get_or_404(id)
    form = UserEditForm(obj=user)
    
    if form.validate_on_submit():
        user.name = form.name.data
        user.role = form.role.data
        db.session.commit()
        flash('用户信息已更新！')
        return redirect(url_for('admin.users'))
    
    return render_template('admin/edit_user.html', title='编辑用户', form=form, user=user)

@bp.route('/users/<int:id>/delete')
@login_required
@admin_required
def delete_user(id):
    user = User.query.get_or_404(id)
    # 防止删除自己
    if user == current_user:
        flash('不能删除当前登录的用户！')
        return redirect(url_for('admin.users'))
    
    db.session.delete(user)
    db.session.commit()
    flash('用户已删除！')
    return redirect(url_for('admin.users'))